package com.keiou.drink.ui.activity;

import android.os.Bundle;
import android.os.Handler;
import android.widget.ImageView;

import com.keiou.drink.R;
import com.keiou.drink.api.AbsSubscriber;
import com.keiou.drink.api.exception.ApiException;
import com.keiou.drink.api.remote.Api;
import com.keiou.drink.api.rx.RxHelper;
import com.keiou.drink.response.MachineStatusRes;
import com.keiou.drink.response.base.HttpResult;
import com.keiou.drink.ui.activity.base.RxActivity;
import com.keiou.drink.util.PrefsHelper;
import com.keiou.drink.util.TDevice;
import com.keiou.drink.util.UIUtil;

import butterknife.BindView;

/**
 * 作者 ：Bob on 2017/10/30.
 * 邮箱 ：motherlovefather@126.com
 * 系统休息
 */

public class RestActivity extends RxActivity {
    @BindView(R.id.iv_status)
    ImageView ivStatus;

    public static final int DELY = 1000 * 30;

    private Handler handler = new Handler();

    @Override
    protected int getLayoutId() {
        return R.layout.activity_result;
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
        ivStatus.setImageResource(R.drawable.rest);
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void loadData() {
        delayLoadData(DELY);
    }

    private void delayLoadData(long delay) {
        if (isFinishing()) {
            return;
        }

        handler.postDelayed(() -> loadStatus(), delay);
    }

    private void loadStatus() {

        if (isFinishing()) {
            return;
        }


        addSubscribe(Api.getInstance().getMachineStatus(PrefsHelper.getDeviceId(this))
                .compose(RxHelper.applySchedulers())
                .subscribe(new AbsSubscriber<HttpResult<MachineStatusRes>>() {
                    @Override
                    public void onNext(HttpResult<MachineStatusRes> result) {
                        MachineStatusRes orderMsgRes = result.getResult();
                        String status = orderMsgRes.getStatus();
                        //机器状态(1：正常）
                        if ("1".equals(status)) {
                            redirectToMain();
                        } else{
                            delayLoadData(DELY);
                        }

                    }


                    @Override
                    protected void onError(ApiException ex) {
                        delayLoadData(3000);
                    }

                    @Override
                    protected void onIntercept(int code) {
                    }
                }));
    }

    @Override
    protected void onDestroy() {
        handler.removeCallbacksAndMessages(null);
        super.onDestroy();
    }

    private void redirectToMain() {
        UIUtil.redirectTo(this, MainActivity.class);
        finish();
    }

}
